import React from 'react'
import {
  Form,
  Input,
  Select,
  Button,
  Table,
  Divider,
  Switch,
  Pagination,
  Popconfirm,
  message,
  Modal
} from 'antd'
import { connect } from 'react-redux'
import {
  maintaskFindBypageApi,
  maintaskDelApi,
  projectFindBypageApi,
  productFindApi,
  resetTaskJobApi,
  stopTaskJobApi
} from '../api/ajax'
import _ from 'lodash'

const FormItem = Form.Item
const Option = Select.Option

export function checkTime(time) {
  try {
    const arr = time.split(';')
    const regexp = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/
    return _.every(arr, v => {
      return regexp.test(v)
    })
  } catch (e) {
    return false
  }
}

const columns = (props, loadData, pageNum, showModal) => [
  {
    title: '任务编号',
    dataIndex: 'taskCode',
    key: '2',
    width: 150
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    key: '3',
    width: 100
  },
  {
    title: '项目单位',
    dataIndex: 'branch',
    key: '16',
    width: 100
  },
  {
    title: '任务状态',
    dataIndex: 'status',
    key: '4',
    width: 100,
    render: (text, record, index) => {
      let obj = {
        1: '正常',
        2: '暂停',
        3: '异常',
        4: '过期'
      }
      return obj[text]
    }
  },
  {
    title: '最近传输文件数',
    dataIndex: 'fileNum',
    key: '6',
    width: 150
  },
  {
    title: '创建时间',
    dataIndex: 'createDate',
    key: '1',
    width: 150
  },
  {
    title: '上次运行时间',
    dataIndex: 'newDate',
    key: '5',
    width: 150
  },
  {
    title: '源产品名称',
    dataIndex: 'productName',
    key: '7',
    width: 100,
    render: (text, record) => (
      <span>
        <span>{text}</span>
        <button className="button-a" onClick={() => showModal(record.sourceId)}>
          查看
        </button>
      </span>
    )
  },
  {
    title: '目标名称',
    width: 100,
    dataIndex: 'userName',
    key: '11'
  },
  {
    title: '目标地址',
    dataIndex: 'address',
    width: 200,
    key: '12'
  },
  {
    title: '更新方式',
    dataIndex: 'updateType',
    key: '9',
    width: 200,
    render: (text, record, index) => {
      let obj = {
        1: '增量',
        2: '差异'
      }
      return obj[text]
    }
  },
  {
    title: '传输方式',
    dataIndex: 'pushType',
    key: '10',
    width: 200,
    render: (text, record, index) => {
      let obj = {
        1: '同步',
        2: 'FTP'
      }
      return obj[text]
    }
  },
  {
    title: '是否包括子文件夹源产品',
    dataIndex: 'isSubFile',
    key: '8',
    width: 200,
    render: (text, record, index) => {
      let obj = {
        1: '是',
        2: '否'
      }
      return obj[text]
    }
  },
  {
    title: '切换',
    fixed: 'right',
    key: '14',
    width: 100,
    render: (text, record) => {
      if (record.status === 1) {
        return (
          <span>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={true}
              onChange={async c => {
                stopTaskJobApi({
                  id: record.id,
                  projectId: record.projectId,
                  taskCode: record.taskCode
                }).then(v => {
                  loadData(pageNum)
                })
              }}
            />
          </span>
        )
      } else if (record.status === 2) {
        return (
          <span>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={false}
              onChange={async c => {
                resetTaskJobApi({
                  id: record.id,
                  projectId: record.projectId,
                  taskCode: record.taskCode
                }).then(() => loadData(pageNum))
              }}
            />
          </span>
        )
      } else {
        return null
      }
    }
  },
  {
    title: '操作',
    fixed: 'right',
    dataIndex: 'option',
    key: '13',
    width: 100,
    render: (text, record) => (
      <span>
        <button
          className="button-a"
          onClick={() => props.history.push(`editTask/${record.id}`)}
        >
          编辑
        </button>
        <Divider type="vertical" />
        <Popconfirm
          title="是否删除此条记录"
          onConfirm={() => {
            const { id } = record
            maintaskDelApi({ id }).then(v => {
              message.success('删除成功')
              loadData(pageNum)
            })
          }}
          onCancel={() => {}}
          okText="是"
          cancelText="否"
        >
          <button className="button-a">删除</button>
        </Popconfirm>
      </span>
    )
  }
]

class Home extends React.Component {
  state = {
    currentPage: 1,
    pageNum: 1,
    pageSize: 5,
    sourceId: '',
    tableSource: [],
    aimsIds: '',
    branch: '',
    projectId: '',
    status: '',
    projectSource: [],
    visible: false,
    productForm: {}
  }

  componentDidMount() {
    const { pageNum } = this.state
    this.loadData(pageNum)
  }

  showModal = async sourceId => {
    productFindApi({ id: sourceId })
      .then(v => {
        this.setState({
          productForm: v,
          visible: true
        })
      })
      .catch(error => {
        message.error('请求超时')
      })
  }

  loadData = pageNum => {
    const {
      pageSize,
      sourceId,
      aimsIds,
      projectId,
      status,
      branch
    } = this.state
    this.setState({ currentPage: pageNum, pageNum })
    projectFindBypageApi().then(v => {
      let {
        list: { results }
      } = v
      if (_.isNil(results)) results = []
      this.setState({
        projectSource: results
      })
    })
    maintaskFindBypageApi({
      pageNum,
      pageSize,
      sourceId,
      aimsIds,
      branch,
      projectId,
      status
    })
      .then(v => {
        let {
          list: { totalRecord, results }
        } = v
        if (_.isNil(results)) results = []
        this.setState({
          totalRecord,
          tableSource: results
        })
      })
      .catch(e => console.error(e))
  }

  render() {
    const { projectSource } = this.state
    return (
      <div className="home">
        <div className="home-head">
          <Form layout="inline">
            <FormItem label="源产品名称">
              <Input
                value={this.state.sourceId}
                type="text"
                onChange={e => this.setState({ sourceId: e.target.value })}
              />
            </FormItem>
            <FormItem label="项目名称">
              <Select
                onChange={v => this.setState({ projectId: v })}
                placeholder="选择一个项目"
                style={{ width: 170 }}
                value={this.state.projectId}
              >
                {projectSource.map(p => (
                  <Option value={p.id} key={p.id}>
                    {p.projectName}
                  </Option>
                ))}
              </Select>
            </FormItem>
            <FormItem label="项目单位">
              <Input
                value={this.state.branch}
                onChange={e => this.setState({ branch: e.target.value })}
              />
            </FormItem>
            <FormItem label="目标名称">
              <Input
                value={this.state.aimsIds}
                onChange={e => this.setState({ aimsIds: e.target.value })}
              />
            </FormItem>
            <FormItem label="任务状态">
              <Select
                onChange={v => this.setState({ status: v })}
                placeholder="请选择"
                style={{ width: 170 }}
                value={this.state.status}
              >
                <Option value={1}>正常</Option>
                <Option value={2}>暂停</Option>
                <Option value={3}>异常</Option>
                <Option value={4}>过期</Option>
              </Select>
            </FormItem>
            <Button
              type="primary"
              onClick={() => this.loadData(this.state.pageNum)}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button
              onClick={() =>
                this.setState(
                  {
                    aimsIds: '',
                    projectId: '',
                    status: '',
                    sourceId: '',
                    branch: ''
                  },
                  () => this.loadData(this.state.pageNum)
                )
              }
            >
              重置
            </Button>
          </Form>
        </div>
        <div className="home-body">
          <div className="home-body-head">
            <h3 className="home-body-head-title">任务中心</h3>
            <Button
              type="primary"
              onClick={() => this.props.history.push('createTask')}
            >
              添加新任务
            </Button>
          </div>
          <Table
            dataSource={this.state.tableSource}
            scroll={{ x: 2200 }}
            columns={columns(
              this.props,
              this.loadData,
              this.state.pageNum,
              this.showModal
            )}
            pagination={false}
            rowKey={record => record.id}
          />
          <div className="home-body-page">
            <Pagination
              total={this.state.totalRecord}
              pageSize={this.state.pageSize}
              current={this.state.currentPage}
              onChange={pageNum => {
                this.setState({ pageNum, currentPage: pageNum })
                this.loadData(pageNum)
              }}
              showTotal={total => `共${total}条数据`}
            />
          </div>
        </div>
        {this.state.visible && (
          <Modal
            visible={this.state.visible}
            title="源产品信息"
            onCancel={() => this.setState({ visible: false })}
            footer={
              <Button
                type="primary"
                onClick={() => this.setState({ visible: false })}
              >
                确定
              </Button>
            }
          >
            源产品编号:
            {this.state.productForm && this.state.productForm.productCode}
            <br />
            源产品名称:
            {this.state.productForm && this.state.productForm.productName}
            <br />
            文件名称:{this.state.productForm && this.state.productForm.fileName}
            <br />
            扩展名:{this.state.productForm && this.state.productForm.extenName}
            <br />
            源地址:
            {this.state.productForm && this.state.productForm.sourceAddress}
            <br />
            可访问目标名称:
            {this.state.productForm && this.state.productForm.userName}
          </Modal>
        )}
      </div>
    )
  }
}

export default connect(state => ({
  state
}))(Home)
